import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';

// 创建axios实例
const service = axios.create({
    timeout: 5000,
    withCredentials: true, // 允许携带Cookie（如果需要）
});

// 请求拦截器：自动添加Token
service.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers.Authorization = `Bearer ${token}`; // 统一格式
    }
    return config;
});

// 响应拦截器：处理Token过期
service.interceptors.response.use(
    response => response,
    error => {
        if (error.response?.status === 401) {
            localStorage.removeItem('token');
            router.push('/login');
            ElMessage.error('登录已过期，请重新登录');
        }
        return Promise.reject(error);
    }
);

export default service;